package com.syqc.monitor.ui.fortify

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.utils.toast
import com.syqc.entity.GpsDetail
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.concurrent.TimeUnit


/**
 *@Author Jasper
 *@Time   2021/1/7
 *@Desc   设防服务
 */
class FortifyService : Service() {
    private var centerLatLng: LatLng? = null
    private var notificationManager: NotificationManager? = null
    private var isNeedCenter = false

    private var subscribe: Disposable? = null

    override fun onBind(intent: Intent): IBinder {
        return FortifyBinder()
    }

    override fun onCreate() {
        super.onCreate()
        notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    fun startRequest(carId: String, radius: Int) {
        isNeedCenter = true
        //15秒定时请求位置
        subscribe = Observable.interval(0, 10, TimeUnit.SECONDS)
            .map {
                ServiceHelper.getRepository().getGpsRInfo("", carId, true, true)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
            }
            .subscribe({
                it.subscribe({ entity ->
                    if (entity.isNullOrEmpty()) {
                        toast(R.string.toast_no_location_msg)
                        return@subscribe
                    }
                    val listBean = entity[0]
                    val latLng = LatLng(listBean.glat.toDouble(), listBean.glng.toDouble())
                    LiveDataBus.get().with("fortify_location").postValue(listBean)
                    if (isNeedCenter) {
                        isNeedCenter = false
                        centerLatLng = latLng

                    } else {
                        if (AMapUtils.calculateLineDistance(centerLatLng, latLng) > radius) {
                            showNotification(listBean)
                        }
                    }
                }, {
                    toast(it.message ?: "")
                })

            }, {
                toast(it.message ?: "")
            })

    }

    fun stopRequest() {
        if (subscribe?.isDisposed == false) subscribe?.dispose()
    }

    override fun onDestroy() {
        LiveDataBus.get().remove("fortify_location")
        super.onDestroy()
        stopForeground(true)
        stopRequest()
        stopSelf()

    }

    //*************************************通知**********************************************
    private val overFortify by lazy { getString(R.string.desc_notification_fortify) }

    private fun showNotification(entity: GpsDetail) {
        val carName = entity.carName
        val carPlate = entity.carPlate
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            val channel = NotificationChannel("fortify", "设防", NotificationManager.IMPORTANCE_HIGH)
            channel.setSound(
                Uri.parse("android.resource://" + packageName + "/" + R.raw.alarm),
                Notification.AUDIO_ATTRIBUTES_DEFAULT
            )
            notificationManager!!.createNotificationChannel(channel)
        }
        val builder = NotificationCompat.Builder(this, "fortify")
        if (carName == carPlate) {
            builder.setContentTitle("$carPlate $overFortify")
        } else {
            builder.setContentTitle("$carPlate($carName) $overFortify")
        }
        builder.setContentText(entity.addr ?: "")
        builder.setAutoCancel(true)
        builder.setOnlyAlertOnce(true)
        // 需要VIBRATE权限
        builder.setDefaults(Notification.DEFAULT_LIGHTS)
        builder.priority = Notification.PRIORITY_DEFAULT

        builder.setSound(Uri.parse("android.resource://" + packageName + "/" + R.raw.alarm))
        builder.setStyle(NotificationCompat.BigTextStyle().bigText(entity.addr ?: "")) //支持长文本


        val notification = builder.build()
        startForeground(0, notification)
        notificationManager!!.notify(0, notification)
    }


    /**
     * 创建Binder对象，返回给客户端即Activity使用，提供数据交换的接口
     */
    inner class FortifyBinder : Binder() {
        // 声明一个方法，getService。（提供给客户端调用）
        // 返回当前对象LocalService,这样我们就可在客户端端调用Service的公共方法了
        val service: FortifyService
            get() = this@FortifyService
    }


}